﻿using GalaSoft.MvvmLight.Command;
using Glorysoft.Auto.Xfw;
using Glorysoft.EAP.Core;
using Glorysoft.EAP.Core.Entities;
using Glorysoft.EAP.Core.Enums;
using Glorysoft.EAP.EAPClient.Common;
using Glorysoft.EAP.EAPClient.Model;
using Serilog.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Glorysoft.EAP.EAPClient.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class SelectWaferViewModel : PopupWindowVM
    {
        private readonly Logger ServiceLogger = XfwContext.EapLogger;
        public delegate void CloseDelegate();
        public event CloseDelegate CloseEvent;
        List<SelectWaferInfo> maps = new List<SelectWaferInfo>();
        public C_LotInfo c_LotInfo = null;
        /// <summary>
        /// Initializes a new instance of the LoginViewModel class.
        /// </summary>
        public SelectWaferViewModel()
        {
            AllWafers = new ObservableCollection<SLotMap>();// 取mes里的list
            foreach (var item in ClientInfo.EQPInfo.LotList[0].SlotMaps)
            {
                if (item.waferState != WaferState.WaferNothing.ToString())
                {
                    AllWafers.Add(item);
                }
            }
            c_LotInfo = new C_LotInfo();
            //test 使用
            //for (int i = 1; i <= 25; i++)
            //{
            //    AllWafers.Add(new SLotMap() {     SlotId = $"{i}",  WaferId = "1", isSelect = false });//eaf5fd
            //}
        }
        public Model.RunService ClientInfo
        {
            get
            {
                return Model.RunService.Current;
            }
        }
        private bool _isSelected = false;

        public bool IsSelected
        {
            get { return _isSelected; }

            set
            {
                _isSelected = value;
                RaisePropertyChanged("IsSelected");
            }
        }

        private ObservableCollection<SLotMap> allWafers = new ObservableCollection<SLotMap>();
        public ObservableCollection<SLotMap> AllWafers
        {
            get { return allWafers; }
            set
            {
                allWafers = value;
                RaisePropertyChanged("AllWafers");
            }
        }
        #region command
        private RelayCommand cancelCmd;
        public RelayCommand CancelCmd
        {
            get { return cancelCmd ?? (cancelCmd = new RelayCommand(Cancel)); }
        }
        public void Cancel()
        {
            try
            {
                if (CloseEvent != null)
                    CloseEvent();
            }
            catch (Exception ex)
            {
                ServiceLogger.Error(string.Format("{0}: {1}", GetType().Name, ex));
            }

            this.Close();

            c_LotInfo.Clear();
            #region old Code
            ////ClientInfo.EQPInfo.LotList = new System.Collections.ObjectModel.ObservableCollection<C_LotInfo>();
            ////ClientInfo.EQPInfo.LotList.Add(new C_LotInfo() { UserId = USEID });
            // ClientInfo.EQPInfo.LotList[0].LotId = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].Qty = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].State = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].ProductId = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].ProberRecipe = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].TesterProgram = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].Probercard = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].LotsStatus = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].StageId = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].Priority = string.Empty;
            // ClientInfo.EQPInfo.LotList[0].SlotMaps = null;
            // ClientInfo.EQPInfo.LotList[0].UNITLIST = null;
            //// ClientInfo.EQPInfo.BtnOk = Visibility.Visible;
            // if (ClientInfo.EQPInfo.LotList[0].UserId == null)
            // {
            //     ClientInfo.EQPInfo.BtnOk = Visibility.Collapsed;
            //     ClientInfo.EQPInfo.Btnclean = Visibility.Collapsed;
            // }
            // else
            // {
            //     ClientInfo.EQPInfo.BtnOk = Visibility.Visible;
            //     ClientInfo.EQPInfo.Btnclean = Visibility.Visible;
            // }
            #endregion

        }


        private RelayCommand confirmCmd;
        public RelayCommand ConfirmCmd
        {
            get { return confirmCmd ?? (confirmCmd = new RelayCommand(WaferConfirmCmd)); }
        }


        public class SelectWaferInfo
        {
            public string Slotid { get; set; }
            public string Waferid { get; set; }
        }

        private void WaferConfirmCmd()
        {
            var tempID = "";
            var mesid = "";
            var assignvalue = "";
            var Value = Dict.Current.TestModevalue;//选片模式
            var AllWaferList = AllWafers.Where(t => t.isSelect == true).ToList();
            var AllMESList = AllWafers.Where(t => t.WaferState == "WaferIn").ToList();
            //ClientInfo.EQPInfo.LotList[0].SelectWafersNeedleMark = new ObservableCollection<SLotMap>();
            foreach (var mesitem in AllMESList)
            {
                var itemslotid = mesitem.SlotId;
                mesid += itemslotid + ";";
            }
            foreach (var item in AllWaferList)
            {
                var selectid = item.WaferId;
                var id = item.SlotId;
                tempID += id + ";";
                maps.Add(new SelectWaferInfo { Slotid = id, Waferid = selectid });
            }
            if (maps.Count == 0)
            {
                //MessageBox.Show(Consts.GetTranslation("Msg_WaferIdInputInfo"), Consts.GetTranslation("Msg_ConfirmInfo"), MessageBoxButton.OK, MessageBoxImage.Warning);
                CMessageBox.Show("请选择测试ID!");
                return;
            }
            else
            {
                Dictionary<string, string> messages = null;
                EAPClient eapclient = new EAPClient();
                //物料不一致时增加数量判断
                if (tempID.Split(";").Count() - 1 > mesid.Split(";").Count() - 1)
                {
                    CMessageBox.Show(Consts.GetTranslation("Msg_WaferIdInputInfoError"));
                    return;
                }
                if (Value == "Assign" && tempID.Split(";").Count() > 2)
                {
                    CMessageBox.Show("指定位置测试，不允许选择多条测试ID，请重新选择!");
                    return;
                }
                else
                {
                    if (Dict.Current.CheckZHMode == "Y")
                    {
                        var markvalue = tempID.TrimEnd(';').Split(";");
                        if (Value == "Assign")//从指定位置测试
                        {
                            var assignid = Convert.ToInt32(markvalue[0]);
                            int begincount = Convert.ToInt32(assignid) - 1;
                            int lastCount = ClientInfo.EQPInfo.LotList[0].SlotMaps.Count() - Convert.ToInt32(assignid) + 1;

                            foreach (var item in ClientInfo.EQPInfo.LotList[0].SlotMaps.ToList().GetRange(begincount, lastCount))
                            {
                                var id = item.SlotId;
                                assignvalue += id + ";";

                            }
                            markvalue = assignvalue.TrimEnd(';').Split(";");
                        }
                        if (markvalue.Count() > 3)
                        {
                            //取值首、中、尾 三片
                            var First = markvalue[0];
                            var Medium = markvalue[markvalue.Length / 2];
                            var Last = markvalue[markvalue.Length - 1];
                            Dict.Current.SelectWaferIdList = First + ";" + Medium + ";" + Last;
                        }
                        else
                        {
                            Dict.Current.SelectWaferIdList = tempID.TrimEnd(';');
                        }
                    }
                    else
                    {
                        Dict.Current.SelectWaferIdList = "";
                    }
                    var result = eapclient.SelectWaferID(ClientInfo.EQPInfo.ProberName, tempID.TrimEnd(';'), mesid.TrimEnd(';'), "false", Dict.Current.SelectWaferIdList,Dict.Current.unitIdList);
                    if (result.ReturnCode == "0")
                    {
                        messages = TranslateMsg.GetTranslation("SelectWaferIDOK", tempID);
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                        }
                    //Dict.Current.SelectWaferIdList = tempID.TrimEnd(';');

                        //  MainViewModel.Current.ShowMsg(MessageType.Info, ClientInfo.EQPInfo.LotList[0].LotId + "：" + "Select No" + tempID.TrimEnd(';'), MessageOrigin.EAP);
                        ClientInfo.EQPInfo.LotList[0].TestID = tempID.Replace(";", " ");  //前台显示测试的id ,id 之间用空格处理了
                        ServiceLogger.Debug($"选择针痕检测WaferId为:{Dict.Current.SelectWaferIdList.TrimEnd(';')}");
                        if (string.IsNullOrEmpty(Dict.Current.SelectWaferIdList) )
                        {
                            Dict.Current.SelectWaferIdList = "0";//不选片，打印成0
                        }
                        if (Dict.Current.EAPName == "EAPServer" || Dict.Current.EAPName == "EAPServer_OCR"||Dict.Current.EAPName == "EAPServer_ETS88")
                        {
                            messages = TranslateMsg.GetTranslation("SlectNeedleMarkDetectionWaferIdOK", Dict.Current.SelectWaferIdList);
                            if (!(messages == null || messages.Count == 0))
                            {
                                ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                                XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);
                            }
                        }
                        }
                    else
                    {
                        messages = TranslateMsg.GetTranslation("SelectWaferIDNG");
                        if (!(messages == null || messages.Count == 0))
                        {
                            ClientInfo.EQPInfo.LotList[0].ShowMsg(MessageOrigin.EAP, MessageType.Info, messages[RunService.Current.ClientLanguage]);
                            XfwContext.DbLogger.Information("EAPClient Tip:" + messages[RunService.Current.ClientLanguage]);

                        }
                    }
                    this.Close();
                    //if (Dict.Current.EAPName != "EAPTelKeysight" || Dict.Current.EAPName != "EAPTelKeysight2" || Dict.Current.EAPName != "EAPTelRaytrex")
                    //{
                    //    C_LotInfo lot = new C_LotInfo();
                    //    lot.NeedleMarkDetectionSelectWaferBox();
                    //}                                    
                }
            }
        }
        #endregion
    }
}